package com.benshou.bsoa.common.configuration;

import com.benshou.bsoa.common.trace.MdcTaskDecorator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 线程调度配置类
 *
 * @author <a href="mailto:liuzhenbang@benshou.com">Liu Zhenbang</a>
 */
@Configuration
@EnableScheduling
public class ScheduleConfig {

    @Value("${task.scheduler.pool-size:5}")
    private int poolSize;

    @Value("${task.scheduler.thread-name-prefix:scheduled-}")
    private String threadNamePrefix;

    /**
     * 注册 ThreadPoolTaskScheduler
     * @return ThreadPoolTaskScheduler
     */
    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(poolSize);
        scheduler.setThreadNamePrefix(threadNamePrefix);
        // 关键：添加MDC上下文传递装饰器
        scheduler.setTaskDecorator(new MdcTaskDecorator());
        return scheduler;
    }

}